package com.yonyou.jrmob.contacts.contact.activity;

/**
 * Created by lzq on 2016/10/27.
 */

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yonyou.jrmob.contacts.R;
import com.yonyou.jrmob.contacts.contact.adapter.SortAdapter_ct;
import com.yonyou.jrmob.contacts.contact.bean.ContactsVO_ct;
import com.yonyou.jrmob.contacts.contact.utils.CharacterParser_ct;
import com.yonyou.jrmob.contacts.contact.utils.PinyinComparator_ct;
import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.bingoogolapple.titlebar.BGATitleBar;
import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.gkh.MAServices_gkh;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.view.auto.AutoCompleteEditView;

public class SearchContactActivity_ct extends BaseActivityMob_lib implements OnItemClickListener {
    private AutoCompleteEditView searchView;
    private AutoCompleteTextView tv;
    private ListView searchListView;
    private List<ContactsVO_ct> contactsList;
    private SortAdapter_ct searchContactAdapter;
    private Drawable mRightDrawable;
    private CharacterParser_ct characterParserCt;
    private PinyinComparator_ct pinyinComparatorCt;
    private Dialog dialog = null;
    private BGATitleBar titleBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initActionbar();
        setContentView(R.layout.search_contact_list_ct);
        StatusBarUtil.StatusBarLightMode(this);
        initView();
        initSerach();
        initData();
        initOnClick();
        initListener();
    }


    @Override
    public void initListener() {

    }

    @Override

    public void initData() {

    }

    @Override
    public void initView() {
        dialog = MobUtils.createLoadingDialog(mActivity, "加载中请稍后...");
        characterParserCt = CharacterParser_ct.getInstance();
        pinyinComparatorCt = new PinyinComparator_ct();
        titleBar = (BGATitleBar) findViewById(R.id.search_title_bar);
        titleBar.setTitleText("通讯录");
        searchView = (AutoCompleteEditView) findViewById(R.id.search_view_pledge);
        searchListView = (ListView) findViewById(R.id.search_contact_list);
        tv = searchView.getTv();
        tv.setFocusable(true);
        tv.setFocusableInTouchMode(true);
        tv.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) tv.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(tv, 0);
            }
        }, 998);
    }

    public void initSerach() {

        // 删除图标
        searchView.getIv().setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                searchView.getTv().setText("");
            }
        });
        // 输入的文本
        searchView.getTv().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                boolean isVisible = searchView.getTv().getText().toString().trim()
                        .length() == 0; // 控制显示与否
                // 空的时候不显示
                if (isVisible) {
                    searchView.getIv().setVisibility(View.INVISIBLE);
                    searchListView.setVisibility(View.INVISIBLE);
                } else {
                    searchView.getIv().setVisibility(View.VISIBLE);

                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        searchView.getTv().setOnEditorActionListener(
                new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE
                                || actionId == EditorInfo.IME_ACTION_GO
                                || actionId == EditorInfo.IME_ACTION_NEXT
                                || actionId == EditorInfo.IME_ACTION_SEARCH) {
                            // 搜索
                            boolean isVisible = searchView.getTv().getText()
                                    .toString().length() >= 1;
                            if (isVisible) {
                                // 搜索
                                String key_word = searchView.getTv().getText()
                                        .toString();
                                if (contactsList != null) {
                                    contactsList.clear();
                                }
                                searchListView.setVisibility(View.VISIBLE);
                                callService(key_word);
                            }
                        }
                        return false;
                    }
                });

        // 默认删除按钮不显示
        searchView.getIv().setVisibility(View.INVISIBLE);
    }

    public void initOnClick() {
        searchListView.setOnItemClickListener(this);
        titleBar.setDelegate(new BGATitleBar.Delegate() {
            @Override
            public void onClickLeftCtv() {
                finish();
            }

            @Override
            public void onClickTitleCtv() {

            }

            @Override
            public void onClickRightCtv() {

            }

            @Override
            public void onClickRightSecondaryCtv() {

            }
        });
    }

    /***
     * 调用后台服务
     * @param key_word
     */
    private void callService(String key_word) {
        JSONObject json = new JSONObject();
        try {
            json.put("transtype", Constant.TRANSTYPE_SEARCH_CONTACT);
            json.put("uuidToken", Constant.TOKEN);
            json.put("tenant_id", getUserInfoLRY().getTenant_id());
            json.put("query", key_word);
            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,请检查!");
                return;
            }
            dialog.show();
            MAServices_gkh.callMACommonService(this, new ServiceCallback() {
                @Override
                public void execute(JSONObject json) {
                    //Toast.makeText(mActivity, json+"", Toast.LENGTH_LONG).show();
                    LogUtils.e("搜索联系人数据：" + json.toString());
                    JSONObject jsObject;
                    JSONArray jsArray;
                    if (null != dialog && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    try {
                        jsObject = (JSONObject) json.opt("result");
                        Object obj = jsObject.opt("retflag");
                        // 有错误的时候
                        if (null != obj && obj.toString().trim().equals("1")) {
                            String msg = jsObject.optString("msg").toString().trim();
                            showMessage(msg);
                            if (msg.contains("请重新登录")) {
                                turnToLoginActivity(SearchContactActivity_ct.this);
                            }
                            return;
                        }
                        jsArray = (JSONArray) jsObject.get("contactsInfo");
                        if (0 == jsArray.length()) {
                            Toast.makeText(SearchContactActivity_ct.this, "请求结果为空！",
                                    Toast.LENGTH_LONG).show();

                            searchView.getTv().setText("");
                            return;
                        }
                        contactsList = new ArrayList<ContactsVO_ct>();
                        for (int i = 0; i < jsArray.length(); i++) {
                            ContactsVO_ct contacts = new ContactsVO_ct();
                            contacts.setContactName(jsArray.getJSONObject(i).getString("user_name").trim());
                            contacts.setVdef(jsArray.getJSONObject(i).getString("user_mobilephone"));
                            contacts.setContactTel(jsArray.getJSONObject(i).getString("user_telephone"));
                            contacts.setUser_email(jsArray.getJSONObject(i).getString("user_email"));
                            contacts.setCuserId(jsArray.getJSONObject(i).getString("cuserid"));
                            contactsList.add(contacts);
                        }
                        contactsList = filledData(contactsList);
                        Collections.sort(contactsList, pinyinComparatorCt);
                        searchContactAdapter = new SortAdapter_ct(SearchContactActivity_ct.this, contactsList, true);
                        searchListView.setAdapter(searchContactAdapter);
                    } catch (JSONException e1) {
                        if (null != dialog && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        e1.printStackTrace();
                    }
                }

                @Override
                public void error(String arg0, String arg1) {
                    if (null != dialog && dialog.isShowing()) {
                        dialog.dismiss();
                    }

                    if (!"".equals(arg1)) {
                        Toast.makeText(SearchContactActivity_ct.this, arg0 + arg1,
                                Toast.LENGTH_LONG).show();
                    }
                }
            }, json);

        } catch (Exception e) {
            if (null != dialog && dialog.isShowing()) {
                dialog.dismiss();
            }
            Log.e("mmmm", e + "");
            e.printStackTrace();
        }

    }

    // 隐藏或者显示右边clean的图标
    protected void setClearDrawableVisible(boolean isVisible) {
        Drawable rightDrawable;
        if (isVisible) {
            rightDrawable = mRightDrawable;
        } else {
            rightDrawable = null;
        }
        // 使用代码设置该控件left, top, right, and bottom处的图标
        /*
		 * textExt.setCompoundDrawables(textExt.getCompoundDrawables()[0],
		 * textExt.getCompoundDrawables()[1], rightDrawable,
		 * textExt.getCompoundDrawables()[3]);
		 */
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // TODO Auto-generated method stub
        String name = searchContactAdapter.getItem(position).getContactName();
        Intent intent = new Intent();
        intent.putExtra("name", name);
        intent.putExtra("cuserId", searchContactAdapter.getItem(position).getCuserId());
        intent.setClass(SearchContactActivity_ct.this, ContactsDetailActivity_ct.class);
        startActivity(intent);
    }

    /**
     * 姓名首字母转换
     */
    private List<ContactsVO_ct> filledData(List<ContactsVO_ct> contactsList) {
        if (contactsList == null) {
            contactsList = new ArrayList<ContactsVO_ct>();
        }
        for (int i = 0; i < contactsList.size(); i++) {
            String pinyin = characterParserCt.getSelling(contactsList.get(i).getContactName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                contactsList.get(i).setSortLetters(sortString.toUpperCase());
            } else {
                contactsList.get(i).setSortLetters("#");
            }
        }
        return contactsList;

    }

}

